package com.jt.service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.jt.mapper.ItemDescMapper;
import com.jt.mapper.ItemMapper;
import com.jt.pojo.Item;
import com.jt.pojo.ItemDesc;
import com.jt.vo.EasyUITable;

@Service
public class ItemServiceImpl implements ItemService {
	
	@Autowired
	private ItemMapper itemMapper;
	@Autowired
	private ItemDescMapper itemDescMapper;

	//分页查询
	@Override
	public EasyUITable findItemByPage(Integer page, Integer rows) {
		int total=itemMapper.selectCount(null);
		int start=(page-1)*rows;//起始位置
		List<Item> itemList=itemMapper.findItemByPage(start, rows);
		return new EasyUITable(total, itemList);
	}

	//新增商品
	@Transactional//事务控制，发生异常时回滚
	@Override
	public void saveItem(Item item,ItemDesc itemDesc) {
		//1.商品数据新增
		item.setStatus(1)//表示正常
			.setCreated(new Date())
			.setUpdated(item.getCreated());
		itemMapper.insert(item);
		//int a=1/0;//测试事务
		
		//2.商品详情新增
		itemDesc.setItemId(item.getId())//mybatis底层做了封装，把商品数据插入商品表之后再把商品ID返回
				.setCreated(item.getCreated())
				.setUpdated(item.getUpdated());
		itemDescMapper.insert(itemDesc);
	}

	//修改商品
	@Transactional
	@Override
	public void updateItem(Item item,ItemDesc itemDesc) {
		//1.修改商品数据
		item.setStatus(1)
			.setUpdated(new Date());
		itemMapper.updateById(item);
		//int a=1/0;//测试事务
		
		//2.修改商品详情
		itemDesc.setItemId(item.getId())
				.setUpdated(item.getUpdated());
		itemDescMapper.updateById(itemDesc);//通过主键修改
	}

	//修改商品状态
	@Transactional
	@Override
	public void updateStatus(Long[] ids, int status) {
		Item item=(Item)new Item()
				.setStatus(status)
				.setUpdated(new Date());//此方式是父类中的，因此要做强类型转换
		UpdateWrapper<Item> updateWrapper=new UpdateWrapper<>();
		List<Long> idList=Arrays.asList(ids);
		updateWrapper.in("id", idList);
		itemMapper.update(item, updateWrapper);
	}

	//删除商品
	@Transactional
	@Override
	public void deleteItem(Long[] ids) {
		List<Long> idList=Arrays.asList(ids);
		itemMapper.deleteBatchIds(idList);
		itemDescMapper.deleteBatchIds(idList);
	}

	//查询商品详情
	@Override
	public ItemDesc findItemDescById(Long itemId) {
		return itemDescMapper.selectById(itemId);
	}

	//根据id查询商品
	@Override
	public Item findItemById(Long itemId) {
		return itemMapper.selectById(itemId);
	}
	
	
	
	
	
	
	
}
